<template>
  <div>
    <a-table :columns="columns" :data-source="data"
             :loading="loading" :defaultExpandedRowKeys="[1]"
             :rowKey="record => record.menuId">
      <template #title>
        <a-row type="flex" justify="space-between">
          <a-col :span="4">
            <a-button type="primary" icon="plus-circle" style="margin-left: 10px;" @click="showAddModal">
              新增菜单
            </a-button>
          </a-col>

          <a-col>
            <a-form-model ref="searchForm"
                          layout="inline" :model="searchForm">
              <a-form-model-item  ref="menuNameLike" prop="menuNameLike">
                <a-input v-model="searchForm.menuNameLike" placeholder="模糊查询菜单名称">
                </a-input>
              </a-form-model-item>

              <a-form-model-item ref="searchStatus" prop="searchStatus">
                <a-select v-model="searchForm.searchStatus" style="width: 200px" placeholder="请选择要查询的菜单状态">
                  <a-select-option value="1">
                    启用
                  </a-select-option>
                  <a-select-option value="0">
                    禁用
                  </a-select-option>
                </a-select>
              </a-form-model-item>

              <a-form-model-item>
                <a-button
                    type="primary"
                    @click="handleSearchFormSubmit"
                    :disabled="searchIsDisable">
                  查询
                </a-button>
                <a-button style="margin-left: 10px;"  @click="resetForm('searchForm')">
                  重置
                </a-button>
              </a-form-model-item>
            </a-form-model>
          </a-col>
        </a-row>


        <!--    Modal Start    -->
        <a-modal
            :title="modal.title"
            :visible="modal.visible"
            :confirm-loading="modal.confirmLoading"
            okText="提交" cancelText="取消"
            @ok="handleModalOk" @cancel="handleModalCancel">

          <a-form-model :model="form" ref="form" @submit="handleModalFormSubmit"
                        :label-col="{span:4}" :wrapper-col="{span:14}" :rules="modal.rules">

            <a-form-model-item label="上级菜单" ref="menuPid" prop="menuPid">
              <a-tree-select
                  v-model="form.menuPid"
                  :disabled="modal.isDisabled"
                  style="width: 100%"
                  :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
                  :tree-data="data"
                  placeholder="请选择父节点"
                  :replaceFields="modal.selectTreeReplaceFields"
              >
              </a-tree-select>
            </a-form-model-item>

            <a-form-model-item label="菜单名称" ref="menuName" prop="menuName">
              <a-input v-model="form.menuName" placeholder="菜单名称"  />
            </a-form-model-item>

            <a-form-model-item label="菜单路由" ref="path" prop="path">

              <a-input v-model="form.path" placeholder="请输入菜单路由" />
            </a-form-model-item>

            <a-form-model-item label="菜单图标" ref="menuIcon" prop="menuIcon">
              <a-input v-model="form.menuIcon" placeholder="请输入菜单图标"  />
            </a-form-model-item>

            <a-form-model-item label="菜单类型" ref="menuType" prop="menuType">
              <a-radio-group v-model="form.menuType" button-style="solid">
                <a-radio-button value="M">
                  菜单
                </a-radio-button>
                <a-radio-button value="B">
                  按钮
                </a-radio-button>
                <a-radio-button value="A">
                  超链接
                </a-radio-button>
                <a-radio-button value="T">
                  标签页
                </a-radio-button>
              </a-radio-group>
            </a-form-model-item>

            <a-form-model-item label="菜单排序" ref="sort" prop="sort">
              <a-input-number v-model="form.sort" :min="1" :max="50" placeholder="菜单排序" />
            </a-form-model-item>

            <a-form-model-item label="是否启用" ref="status" prop="status">
              <a-radio-group v-model="form.status" button-style="solid">
                <a-radio-button value="1">
                  启用
                </a-radio-button>
                <a-radio-button value="0">
                  禁用
                </a-radio-button>
              </a-radio-group>
            </a-form-model-item>

          </a-form-model>
        </a-modal>
        <!--    Modal End    -->
      </template>

      <template #menuIcon="menuIcon">
        <span v-if="menuIcon!==''">
          <a-icon :type="menuIcon" />
          {{menuIcon}}
        </span>
        <span v-else>
           {{menuIcon}}
        </span>

      </template>

      <template #status="status">
        <a-tag :color="status?'green':'volcano'">
          <span v-if="status">启用</span>
          <span v-else>禁用</span>
        </a-tag>
      </template>

      <template #action="record">
        <a-button type="primary" shape="circle" icon="edit" @click="showEditModal(record)" />
        <a-divider type="vertical" />
        <a-popconfirm
            :title="`确认要删除:${record.menuName}吗?`"
            ok-text="确认"
            cancel-text="取消"
            @confirm="handleDeleteMenu(record.menuId)"
        >
          <a-icon slot="icon" type="question-circle-o" style="color: red" />
          <a-button type="danger" shape="circle" icon="delete" />
        </a-popconfirm>

      </template>

    </a-table>
  </div>
</template>

<script>
import {getMenuTree,addMenu,deleteMenuById,updateMenu} from "@/api/menu";

const columns = [
  {
    title: '菜单标识',
    dataIndex: 'menuId',
    key: 'menuId',
  },
  {
    title: '菜单名称',
    dataIndex: 'menuName',
    key: 'menuName',
  },
  {
    title: '菜单路由',
    dataIndex: 'path',
    key: 'path',
  },
  {
    title: '菜单图标',
    dataIndex: 'menuIcon',
    key: 'menuIcon',
    scopedSlots: { customRender: 'menuIcon' }
  },
  {
    title: '排序',
    dataIndex: 'sort',
    key: 'sort',
  },
  {
    title: '菜单类型',
    dataIndex: 'menuType',
    key: 'menuType',
  },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status',
    scopedSlots: { customRender: 'status' },
  },
  {
    title: '操作',
    key: 'action',
    scopedSlots: { customRender: 'action' },
  }
];
const selectTreeReplaceFields = {
  children:'children',
  title:'menuName',
  key:'menuId',
  value: 'menuId'
}
const rules = {
  menuPid: [
    {required: true, message: '请选择上级菜单',trigger:['blur','change']},
  ],
  menuName: [
    {required: true, message: '请输入菜单名称', trigger: ['blur']},
  ],
  path:[
    {required: true, message: '请输入菜单路由', trigger: ['blur']}
  ],
  menuType:[
    {required: true, message: '请选择菜单类型', trigger: 'blur'}
  ],
  sort: [
    {required: true, message: '请输入当前菜单在同级菜单内的排序序号', trigger: 'blur'},
  ],
  status:[
    {required: true, message: '请选择是否启用', trigger: 'blur'}
  ]
}
export default {
  name: "SystemMenu",
  mounted() {
    this.getTreeData()
  },
  data() {
    return {
      data:[],
      columns,
      loading:false,
      searchFromSetting:{
        isDisable:true,
        isHandleSubmit:false
      },
      searchForm:{
        menuNameLike:'',
        searchStatus:undefined
      },
      modal:{
        title:'',
        visible:false,
        confirmLoading: false,
        isDisabled:false,
        selectTreeReplaceFields,
        rules
      },
      form:{
        menuId:undefined,
        menuPid:undefined,
        menuName:'',
        path:'',
        menuIcon:'',
        sort:'',
        status:undefined,
        menuType:''
      }
    };
  },
  methods:{
    handleSearchFormSubmit(){
      console.log(this.searchForm)
      this.isHandleSubmit = true;
      let submitParams = {
        rootMenuId:1
      }
      if (this.searchForm.apiNameLike!==''){
        submitParams['menuNameLike'] = this.searchForm.apiNameLike
      }
      if (typeof (this.searchForm.searchStatus)!=='undefined'){
        submitParams['menuStatus']=this.searchForm.searchStatus==='1'
      }
      console.log('SystemMenu handleSearchFormSubmit',submitParams)
      this.getTreeData(submitParams)
    },
    resetSearchForm(){
      this.$refs.searchFrom.resetFields();
      if (this.searchFromSetting.isHandleSubmit){
        this.getTreeData()
      }
    },
    getTreeData(param= {rootMenuId:1}){
      this.loading = true
      getMenuTree(param).then(res=>{
        this.data = res.data
      }).catch(err=>{
        console.log("SystemMenu:getTreeData:"+err.message);
      }).finally(()=>{
        this.loading = false
      })
    },
    showAddModal(){
      this.modal.title = '新增菜单'
      this.modal.visible = true
      this.modal.isDisabled = false;
    },
    showEditModal(record){
      this.modal.title = '修改菜单'
      this.modal.visible = true
      this.modal.isDisabled = true;
      let {menuId, menuPid, menuName, path, menuIcon, sort, status, menuType} = record
      this.form = {
        menuId, menuPid, menuName, path, menuIcon, sort, menuType,
        status:status?"1":"0"
      }
    },
    handleModalOk(){
      this.handleModalFormSubmit()
    },
    handleModalCancel(){
      this.resetForm('form')
      this.modal.visible = false
    },
    resetForm(formName) {
      this.form = {
        menuId:undefined,
        menuPid:undefined,
        menuName:'',
        path:'',
        menuIcon:'',
        sort:'',
        status:undefined,
        menuType:''
      }
      this.$refs[formName].resetFields();
    },
    handleModalFormSubmit(){
      this.$refs['form'].validate(valid=>{
        if (valid) {
          let submitData = this.form
          submitData.status = this.form.status === "1"
          this.modal.confirmLoading = true
          if (this.modal.isDisabled){
            this.handleUpdateMenu(submitData)
          }else {
            this.handleAddMenu(submitData)
          }
        } else {
          this.handleFiled(new Error('表单校验不通过'))
          return false;
        }

      })
    },
    handleUpdateMenu(param){
      updateMenu(param).then(res=>{
        this.handleSuccess(res)
        this.resetForm('form')
      }).cache(err=>{
        this.handleFiled(err)
      })
    },
    handleAddMenu(param){
      addMenu(param).then(res=>{
        this.handleSuccess(res)
        this.resetForm('form')
      }).cache(err=>{
        this.handleFiled(err)
      })
    },
    handleDeleteMenu(menuId){
      deleteMenuById(menuId).then(res=>{
        this.handleSuccess(res)
      }).cache(err=>{
        this.handleFiled(err)
      })
    },
    handleSuccess(res){
      this.modal.confirmLoading = false
      this.$notification['success']({
        message: '成功',
        description: `${res.data}`,
        duration: 4
      })
      this.getTreeData()
    },
    handleFiled(err){
      this.modal.confirmLoading = false
      console.log(err.message)
      this.$notification['error']({
        message: '错误',
        description: ((err.response || {}).message || {}).message||err.message || '请求出现错误，请稍后再试',
        duration: 4
      })
    }
  },
  computed:{
    searchIsDisable(){
      return this.searchForm.menuNameLike===''&&!this.searchForm.searchStatus;
    }
  }
}

</script>

<style scoped>

</style>
